package com.cliang.controller;

import com.cliang.entity.BlogUser;
import com.cliang.tools.Tools;
import com.cliang.tools.db.DB;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Controller
@RequestMapping(value = "/private/")
public class BlogController {

    @RequestMapping(value = "addBlog",method = RequestMethod.POST)
    @ResponseBody
    public void addBlog(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        String title=request.getParameter("title");
        String author=request.getParameter("author");
        String type=request.getParameter("type");
        String content=request.getParameter("editorValue");

        String msg="";
        PrintWriter printWriter=response.getWriter();
        HttpSession session=request.getSession();
        BlogUser blogUser= (BlogUser) session.getAttribute("loginUser");

        Connection conn= DB.getConnection();
        if(conn!=null){
            try {
                PreparedStatement psmt=conn.prepareStatement("insert into Blog.blog(B_uid, B_tid, B_title,B_author, B_content,B_time) VALUES (?,?,?,?,?,?)");
                psmt.setInt(1,blogUser.getBuId());
                psmt.setInt(2,Integer.parseInt(type));
                psmt.setString(3,title);
                psmt.setString(4,author);
                psmt.setString(5,content);
                psmt.setString(6, Tools.getCurrentDate());
                psmt.executeUpdate();
                msg="添加成功！";
            } catch (SQLException e) {
                msg="系统内部错误，请稍后再试！";
                e.printStackTrace();

            }
            DB.close(conn);
        }else {
            msg="系统内部错误，请稍后再试！";
        }

        printWriter.write(msg);
    }

    @RequestMapping(value = "allBlogs")
    @ResponseBody
    public void allBlogs(){

    }
}
